<?php
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/views/GeneralView.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/models/interfaces/IProduct.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/daos/ProductDAO.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/controlers/interfaces/IController.php');

/**
 * @access public
 * @author Edgar Morán
 * @package Aplicación.controlers
 */
class ProductsController implements IController {
	/**
	 * @AssociationType Aplicación.views.GeneralView
	 * @AssociationKind Composition
	 */
	public $_generalView;
	/**
	 * @AssociationType Aplicación.models.interfaces.IProduct
	 * @AssociationKind Composition
	 */
	public $_iProduct;
	/**
	 * @AssociationType Aplicación.daos.ProductDAO
	 * @AssociationKind Composition
	 */
	public $_productDAO;
    
    /**
     * Constructor for class
     */
    public function __construct(){
        $this->_generalView = null;
        $this->_iProduct = null;
        $this->_productDAO = new ProductsDAO();
    }

	/**
	 * @access public
	 * @param int aId
	 * @param aQuantity int
	 * @return boolean
	 * @ParamType aId int
	 * 
	 * @ReturnType boolean
	 */ //Restock?
	public function fillinProducts() {
        $aId = $params['id'];
        $aQuantity_int = $params['quantity'];
        
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
        $valid->validVariable($aQuantity_int, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
        
        if($this->_productDAO->existProduct($aId)){
            $this->_iProduct = $this->createProductObject($this->_productDAO->getProduct($aId));
            $this->_iProduct->setStock($this->_iProduct->getStock() + $aQuantity_int);
        }
	}
    
    /**
     * @param array $array Product information whithin an array with database field names as array keys.
     * @return Product
     */
    public function createProductObject($param){
            $aCode = $param['code']; //string
            $aReference = $param['reference']; //string
            $aName = $param['name']; //string
            $aDescription = $param['description']; //string
            $aPresentation = $param['presentation']; //string
            $aPicture = null; //string
            $aStock = $param['stock']; //int
            $aMinStock = $param['minStock']; //int
            $aPrice = $param['price']; //float
            $aAccess = $param['access']; //float
            
            if($this->validateProductParams($aCode, $aReference, $aName, $aDescription, $aPresentation, $aPicture, $aStock, $aMinStock, $aPrice, $aAccess)){
                $prod = new Product($aCode, $aReference, $aName, $aDescription, $aPresentation, $aPicture, $aStock, $aMinStock, $aPrice, $aAccess);
                return $prod;
            }
            else return null;
    }
    
	/**
	 * @access public
	 * @return array
	 * @ReturnType array
	 */
    public function validateProductParams($aCode, $aReference, $aName, $aDescription, $aPresentation, $aPicture, $aStock, $aMinStock, $aPrice, $aAccess){
		$errors=NULL;
		$validState=true;
		$valid = new Validations();
		$valid->validVariable('presentation', $aPresentation, true , 'enum', 6, 9, NULL, NULL, array('caja_1','caja_2','botella_1','botella_2'));
		$valid->validVariable('access', $aAccess, true , 'enum', 1, 1, NULL, NULL, array('t', 'f'));
		$valid->validVariable('price', $aPrice, true,'int', 1, 9999999999);
		$valid->validVariable('stock', $aStock, true,'int', 1, 9999999999);
		$valid->validVariable('minStock', $aMinStock, true,'int', 1, 9999999999);
		$valid->validVariable('code', $aCode, true, 'string', 2, 200);
		$valid->validVariable('reference', $aReference, true, 'string', 2, 200);
		$valid->validVariable('name', $aName, true, 'string', 2, 200);
		$valid->validVariable('description', $aDescription, true, 'string', 5, 200);
        $valid->validFile('picture', $_FILES['picture'], IMGMAXSIZE, IMGFORMATS);
        
		if ($valid->hasError()){
			//print_r($valid->getErrors());
			$errors=$valid->getErrors();
			$validState=false; 
		}
        
        if($validState && $this->_productDAO->existProductCode($aCode)){
			//echo "si";
			$errors['code']=str_replace('$', $aCode, ERRORAddProductExistProductCode) ;
			//$errors['email']=
			$this->_actionErrors=$errors;
			$validState=false;
        }
        
		$this->_actionErrors=$errors;	
			
		return $validState;        
    }

	/**
	 * @access public
	 * @return array
	 * @ReturnType array
	 */
	public function listProductsUnderMinimumLevel() {
        return $this->_productDAO->listProductsUnderMinimumLevel();
	}

	/**
	 * @access public
	 * @return boolean
	 * @ReturnType boolean
	 */
	public function sendReorderNotification() {
        if($this->_productDAO->howManyProductsUnderMinimumLevel() > 0){
            $products = $this->_productDAO->listProductsUnderMinimumLevel();
            //send email with retrieved information
        }
        else{
            //Mensaje indicando que no hay productos para enviar notificación
        }
	}

	/**
	 * @access public
	 * @return boolean
	 * @ReturnType boolean
	 */
	public function addProduct() {
        
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLaddProduct);
		$util = new Validations();
		$successMessage= NULL;
        
		$view->tpl->pageTitle="Agregar Producto";
		$view->tpl->actionTitle="Agregar producto";
		$view->tpl->actionError=false;
        
		$params['presentations']= array(
			array(
		      "value" => '',
		      "name" => 'Seleccione el tipo de presentación',
		      "selected" => true
		    ),
		    array(
		      "value" => 'caja_1',
		      "name" => 'Caja individual',
		      "selected" => false
		    ),
		    array(
		      "value" => 'caja_2',
		      "name" => 'Caja de 2 unidades',
		      "selected" => false
		    ),
		    array(
		      "value" => 'botella_1',
		      "name" => 'Botella de 200 ml',
		      "selected" => false
		    ),
		    array(
		      "value" => 'botella_2',
		      "name" => 'Botella de 500 ml',
		      "selected" => false
		    ),
		);
        
		$params['accesss']= array(
			array(
		      "value" => 't',
		      "name" => 'Si',
		      "selected" => true
		    ),
		    array(
		      "value" => 'f',
		      "name" => 'No',
		      "selected" => false
		    ),
		);
        
        
		//si se va a agregar un producto
    	if(!empty($params['submit'])){
            $this->_iProduct = $this->createProductObject($params);
            if($this->_iProduct != null && isset($this->_iProduct)){
                $file = $this->saveFile($_FILES['picture']);
                $this->_iProduct->setPicture($file);
                echo "file name: ".$file."<br>";
                if($this->_productDAO->addProduct($this->_iProduct)){
                    setCookieLive ("MensajeExito", str_replace('$', $aName." ".$aLastName, SUCCESSAddProduct) , time()+3600);
                    //echo "si";
                    header('Location:'.ADDPRODUCT);
                }
                else {
                    $view->tpl->actionError=ERRORDB;
                }
            }
            else{
                //error con los parámetros de entrada
                $seletecValue=$util->array_search_key($params['presentation'],$params['presentations']);
                
                if(!empty($seletecValue)){
                    $params['presentations'][0]['selected']=false;
                    $params['presentations'][$seletecValue]['selected']=true;
                }
                $seletecValue=$util->array_search_key($params['access'],$params['accesss']);
                if(!empty($seletecValue)){
                    $params['accesss'][0]['selected']=false;
                    $params['accesss'][$seletecValue]['selected']=true;
                }
                
				$view->tpl->actionError=ERRORGeneral;
				$view->tpl->actionErrors=$this->_actionErrors;
            }
        
        }
		else{
			if(isset($_COOKIE['MensajeExito']))
				$successMessage=$_COOKIE['MensajeExito'];
			removeCookieLive('MensajeExito');
		}
		$view->tpl->params=$params;
		$view->tpl->successMessage=$successMessage;
		//$view->tpl->categoryList =
		$result = $view->render();    
		$fc->setBody($result);
    }
    
	/**
	 * @access public
	 * @param array file
	 * @return boolean
	 * @ParamType file array
	 * @ReturnType boolean
	 */
    public function saveFile($file){
        list($nombre, $ext) = explode("\.",$file['name']);
        $ahora = date("Gis");
        $dir = IMGUPLOAD;
        $nombre = basename($this->cleanSpecialChars($nombre)."_".$ahora.".".strtolower($ext));
        $path = $dir.$nombre;
        @move_uploaded_file($file['tmp_name'], $path) or $view->tpl->actionError=ERRORSaveFile;
        echo $path;
        exit();
        return $nombre;
    }
    
	/**
	 * @access public
	 * @param string file
	 * @return boolean
	 * @ParamType file array
	 * @ReturnType boolean
	 */
	function cleanSpecialChars($string){
		$string  = str_replace('á', 'a', $string);
		$string  = str_replace('Á', 'A', $string);
		$string  = str_replace('é', 'e', $string);
		$string  = str_replace('É', 'E', $string);
		$string  = str_replace('í', 'i', $string);
		$string  = str_replace('Í', 'I', $string);
		$string  = str_replace('ó', 'o', $string);
		$string  = str_replace('Ó', 'O', $string);
		$string  = str_replace('ú', 'u', $string);
		$string  = str_replace('Ú', 'U', $string);
		$string  = str_replace('¡', '', $string);
		$string  = str_replace('¿', '', $string);
		$string  = str_replace('ñ', 'n', $string);
		$string  = str_replace('Ñ', 'N', $string);
		$string  = str_replace('"', '', $string);
		$string  = str_replace("&", '', $string);
		$string  = str_replace("#", '', $string);
		$string  = str_replace("@", '', $string);
		$string  = str_replace("$", '', $string);
		$string  = str_replace("%", '', $string);
		$string  = str_replace("^", '', $string);
		$string  = str_replace("*", '', $string);
		$string  = str_replace("(", '', $string);
		$string  = str_replace(")", '', $string);
		$string  = str_replace("-", '_', $string);
		$string  = str_replace("+", '', $string);
		$string  = str_replace("=", '', $string);
		$string  = str_replace("~", '', $string);
		$string  = str_replace("`", '', $string);
		$string  = str_replace(";", '', $string);
		$string  = str_replace(":", '', $string);
		$string  = str_replace("{", '', $string);
		$string  = str_replace("}", '', $string);
		$string  = str_replace("|", '', $string);
		$string  = str_replace("\\", '', $string);
		$string  = str_replace(",", '', $string);
		$string  = str_replace('<', '', $string);
		$string  = str_replace('>', '', $string);
		$string  = str_replace(' ', '_', $string);
		return $string;
	}    
	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function deactivateProduct($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_productDAO->deactivateProduct($aId);
	}

	/**
	 * @access public
	 * @param int aId
	 * @return Aplicación.models.interfaces.IProduct
	 * @ParamType aId int
	 * @ReturnType Aplicación.models.interfaces.IProduct
	 */
	public function getProduct($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		$prod = $this->_productDAO->getProduct($aId);
        if ($prod != false){
            $this->_iProduct = new Product($aCode, $aReference, $aName, $aDescription, $aPresentation, $aPicture, $aStock, $aMinStock, $aPrice, $aAccess);
            return $this->_iProduct;
        }
        return false;
	}

	/**
	 * @access public
	 * @param int aId
	 * @return void
	 * @ParamType aId int
	 * @ReturnType void
	 */
	public function printProduct($aId) {
		// Not yet implemented
	}

	/**
	 * @access public
	 * @return array
	 * @ReturnType array
	 */
	public function getProducts() {
		return $this->_productDAO->getProducts();
	}

	/**
	 * @access public
	 * @return void
	 * @ReturnType void
	 */
	public function printProductsList() {
		// Not yet implemented
	}
    
    /**
	 * @access public
	 * @return void
	 * @ReturnType void
	 */
	public function listProducts() {
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLlistProducts);
		$view->tpl->hasItems=false;
		
		$view->tpl->pageTitle="Listar Productos";
		$view->tpl->actionTitle="Listado de Productos";
		
		if ($this->_productDAO->howManyProducts()){
			$view->tpl->hasItems=$this->_productDAO->howManyProducts();
			$products=$this->getProducts();
            
			$needle=array( array ('key'=>'presentation', 'search'=> 'caja_1', 'replace'=>'Caja individual'),
							array ('key'=>'presentation', 'search'=> 'caja_2', 'replace'=>'Caja de 2 unidades'),
							array ('key'=>'presentation', 'search'=> 'botella_1', 'replace'=>'Botella de 200 ml'),
							array ('key'=>'presentation', 'search'=> 'botella_2', 'replace'=>'Botella de 500 ml') );            
			$products=arrayReplace($needle, $products);
            
			$needle=array( array ('key'=>'access', 'search'=> 't', 'replace'=>'Si'),
							array ('key'=>'access', 'search'=> 'f', 'replace'=>'No') );
			$products=arrayReplace($needle, $products);
            
			$view->tpl->products=$products;
			
		}
		$result = $view->render();    
		$fc->setBody($result);
	}

	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function activateProduc($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_productDAO->deactivateProduct($aId);
	}

	/**
	 * @access public
	 * @param string aSearchString
	 * @return array
	 * @ParamType aSearchString string
	 * @ReturnType array
	 */
	public function searchProducts($aSearchString) {
        $valid = new Validations();
        $valid->validVariable($aSearchString, true,'string', 1, 100);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_productDAO->searchProduct($aSearchString);
	}
}
?>